
#include "commandparser.h"
#include "command.h"

#include <stdlib.h>
#include <string.h>
#include <iostream>


#define CMD_EXIT "exit"

using namespace std;

vector<string> CommandParser::split(string cmd, char c) {

	char *tok;
	char *cstr = strdup(cmd.c_str());
	vector<string> toks;

	tok = strtok(cstr, &c);
	while (NULL != tok) {
		toks.push_back(string(tok));
		tok = strtok(NULL, &c);
	}

	delete cstr;

	return toks;

}


Command CommandParser::parse(string str) {

	Command ret;

	vector<string> cmds = CommandParser::split(str, '|');

	for (unsigned int i = 0; i < cmds.size(); i++) {
		vector<string> args = CommandParser::split(cmds[i], ' ');
		if (0 == args[0].compare(CMD_EXIT))
		{
		  cout << "Und aus!" << endl;
		  exit(0);
		}
		if (i == cmds.size() - 1 && 0 == args.back().compare("&")) {
			args.pop_back();
			ret.setBg();
		}
		ret.add(args);
	}

	return ret;

}
